/**
 * Created by joy on 25/09/2017.
 */
import TimeUtil from 'js-common-modules/lib/utils/TimeUtil'

export default class Sqlite {
  constructor (sqliteHelper) {
    this._sqliteHelper = sqliteHelper
  }

  async initTables () {
    await Promise.all([
      this._sqliteHelper.createBySql(`
        CREATE TABLE IF NOT EXISTS blocks
        (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          hash varchar(100) UNIQUE,
          prehash varchar(100) UNIQUE,
          tx_hashs text,
          created_at text
        )
      `),
      this._sqliteHelper.createBySql(`
        CREATE TABLE IF NOT EXISTS transactions
        (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          hash varchar(100) UNIQUE,
          amount real,
          fee real,
          sender_address varchar(100),
          reveiver_address varchar(100),
          type tinyint(4),
          created_at text
        )
      `),
      this._sqliteHelper.createBySql(`
        CREATE TABLE IF NOT EXISTS candidates
        (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          amount real,
          address varchar(100),
          created_at text
        )
      `),
    ])
    // 测试数据
    await this._sqliteHelper.batchInsert({
      batchInsert: [
        ['hash', 'prehash', 'tx_hashs', 'created_at'],
        [
          ['sfhsfghh1', 'coinbase', '["ghghsghs", "dhghwghsgh"]', TimeUtil.toMysqlDateTime(Date.now())],
          ['sfhsfghh2', 'sfhsfghh1', '["ghghsghs", "dhghwghsgh"]', TimeUtil.toMysqlDateTime(Date.now())],
          ['sfhsfghh3', 'sfhsfghh2', '["ghghsghs", "dhghwghsgh"]', TimeUtil.toMysqlDateTime(Date.now())]
        ]
      ],
      from: 'blocks',
      if: () => {
        return false
      }
    })

    logger.info('数据库表准备完毕')
  }

}
